/**
 * 文档详情页
 * Phase 1: 前端 MVP 使用
 * 
 * 功能：
 * - 文档内容展示
 * - 目录(TOC)导航
 * - 侧边栏导航
 * - 面包屑
 * - 元信息展示
 */

import React, { useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import { useQuery } from '@tanstack/react-query';
import { Container } from '@/components/ui/container';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { Skeleton } from '@/components/ui/skeleton';
import { Breadcrumb, BreadcrumbItem, BreadcrumbLink, BreadcrumbList, BreadcrumbPage, BreadcrumbSeparator } from '@/components/ui/breadcrumb';
import DocNav from '@/components/documentation/doc-nav';
import MarkdownRenderer from '@/components/documentation/markdown-renderer';
import TableOfContents from '@/components/documentation/table-of-contents';
import FileList from '@/components/documentation/file-list';
import ImageUploader from '@/components/documentation/image-uploader';
import { documentService, categoryService } from '@/lib/api/services/documentation-service';
import { fileService } from '@/lib/api/services/file-service';
import { loadContent } from '@/lib/api/mock-data/utils/content-loader';
import { usePdfExport } from '@/hooks/use-pdf-export';
import {
  Dialog,
  DialogContent,
  DialogHeader,
  DialogTitle,
  DialogDescription
} from '@/components/ui/dialog';
import {
  Eye,
  Calendar,
  User,
  Edit,
  Share,
  ThumbsUp,
  ArrowLeft,
  Home,
  Maximize2,
  X,
  FileDown,
  Loader2,
  Upload,
  Paperclip
} from 'lucide-react';

const DocDetailPage = () => {
  const { slug } = useParams();
  const navigate = useNavigate();
  
  // 全屏状态管理
  const [isFullscreen, setIsFullscreen] = React.useState(false);
  
  // PDF 导出功能
  const { exportToPdf, isExporting } = usePdfExport();
  

  // 文档详情页不需要上传对话框（附件管理在编辑页面进行）
  
  // 监听 ESC 键退出全屏
  useEffect(() => {
    const handleEscape = (e) => {
      if (e.key === 'Escape' && isFullscreen) {
        setIsFullscreen(false);
      }
    };
    
    window.addEventListener('keydown', handleEscape);
    return () => window.removeEventListener('keydown', handleEscape);
  }, [isFullscreen]);

  // 获取文档详情
  const {
    data: docData,
    isLoading,
    error
  } = useQuery({
    queryKey: ['documents', 'detail', slug],
    queryFn: () => documentService.getBySlug(slug),
    enabled: !!slug
  });

  // 获取分类数据
  const { data: categoriesData } = useQuery({
    queryKey: ['documents', 'categories'],
    queryFn: () => categoryService.getAll()
  });

  // 获取所有文档（用于填充到分类中）
  const { data: allDocumentsData } = useQuery({
    queryKey: ['documents', 'all-for-nav'],
    queryFn: () => documentService.getList({ pageSize: 1000 }), // 获取所有文档
    staleTime: 60000 // 缓存60秒
  });

  // Phase 3: 获取文档关联的文件列表
  const {
    data: filesData,
    isLoading: filesLoading,
    refetch: refetchFiles
  } = useQuery({
    queryKey: ['files', 'document', docData?.id],
    queryFn: () => fileService.getByDocumentId(docData.id),
    enabled: !!docData?.id,
    staleTime: 30000 // 缓存30秒
  });

  const files = filesData || [];

  // 将文档填充到分类树中
  const categories = React.useMemo(() => {
    // 处理 Mock 和 API 的不同数据结构
    const cats = Array.isArray(categoriesData)
      ? categoriesData
      : (categoriesData?.data || []);
    
    if (!cats || cats.length === 0) return [];
    
    const allDocuments = Array.isArray(allDocumentsData)
      ? allDocumentsData
      : (allDocumentsData?.data || []);
    
    // 递归函数：为分类添加documents字段
    const fillDocuments = (categories) => {
      return categories.map(cat => ({
        ...cat,
        documents: allDocuments.filter(doc => doc.categoryId === cat.id),
        children: cat.children ? fillDocuments(cat.children) : []
      }));
    };
    
    return fillDocuments(cats);
  }, [categoriesData, allDocumentsData]);

  // docData 已经是 result.data
  const doc = docData;

  // 根据 categoryId 递归构建完整的分类路径
  const getCategoryPath = React.useMemo(() => {
    if (!doc?.categoryId || !categoriesData) return [];
    
    const cats = Array.isArray(categoriesData)
      ? categoriesData
      : (categoriesData?.data || []);
    
    // 递归查找分类并构建路径
    const findCategoryPath = (categories, targetId, path = []) => {
      for (const cat of categories) {
        const currentPath = [...path, { id: cat.id, name: cat.name, slug: cat.slug }];
        
        if (cat.id === targetId) {
          return currentPath;
        }
        
        if (cat.children && cat.children.length > 0) {
          const found = findCategoryPath(cat.children, targetId, currentPath);
          if (found) return found;
        }
      }
      return null;
    };
    
    return findCategoryPath(cats, doc.categoryId) || [];
  }, [doc?.categoryId, categoriesData]);

  // 加载文档内容（处理多种内容来源）
  const [loadedContent, setLoadedContent] = React.useState('');
  const [contentLoading, setContentLoading] = React.useState(false);
  const [contentError, setContentError] = React.useState(null);

  useEffect(() => {
    async function loadDocContent() {
      if (!doc) {
        setLoadedContent('');
        return;
      }

      // 如果 contentType 是 direct 或已有 content，直接使用
      if (doc.contentType === 'direct' || (doc.content && doc.content.trim())) {
        setLoadedContent(doc.content || '');
        return;
      }

      // 否则，需要根据 contentType 加载内容
      setContentLoading(true);
      setContentError(null);

      try {
        const content = await loadContent({
          contentType: doc.contentType,
          content: doc.content,
          contentPath: doc.contentPath,
          contentUrl: doc.contentUrl,
          contentBase64: doc.contentBase64
        });
        setLoadedContent(content);
      } catch (error) {
        console.error('加载文档内容失败:', error);
        setContentError(error.message);
        setLoadedContent(`# ⚠️ 内容加载失败\n\n${error.message}`);
      } finally {
        setContentLoading(false);
      }
    }

    loadDocContent();
  }, [doc?.id, doc?.contentType, doc?.content, doc?.contentPath, doc?.contentUrl, doc?.contentBase64]);

  // 设置页面标题
  useEffect(() => {
    if (doc?.title) {
      document.title = `${doc.title} - 技术文档`;
    }
    return () => {
      document.title = '技术文档管理系统';
    };
  }, [doc?.title]);

  // 格式化日期
  const formatDate = (dateString) => {
    return new Date(dateString).toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  };

  // 分享功能
  const handleShare = async () => {
    const url = window.location.href;
    try {
      if (navigator.share) {
        await navigator.share({
          title: doc.title,
          text: doc.summary,
          url
        });
      } else {
        await navigator.clipboard.writeText(url);
        alert('链接已复制到剪贴板');
      }
    } catch (error) {
      console.error('分享失败:', error);
    }
  };

  // 导出为 PDF 功能
  const handleExportPdf = async () => {
    try {
      // 获取文档内容容器
      const contentElement = document.querySelector('article.prose');
      
      if (!contentElement) {
        alert('未找到文档内容，请稍后重试');
        return;
      }

      // 导出配置
      await exportToPdf(contentElement, {
        filename: `${doc.title}.pdf`,
        margin: 0.5,
        image: { type: 'jpeg', quality: 0.98 },
        html2canvas: { 
          scale: 2,
          useCORS: true,
          logging: false
        },
        jsPDF: { 
          unit: 'in', 
          format: 'a4', 
          orientation: 'portrait' 
        }
      });
    } catch (error) {
      console.error('导出 PDF 失败:', error);
      alert(`导出失败: ${error.message}`);
    }
  };

  // 加载状态
  if (isLoading) {
    return (
      <div className="flex min-h-screen bg-background">
        {/* 侧边栏骨架屏 */}
        <div className="w-64 border-r bg-card p-4 space-y-4">
          <Skeleton className="h-8 w-32" />
          <Skeleton className="h-6 w-full" />
          <Skeleton className="h-6 w-full" />
          <Skeleton className="h-6 w-3/4" />
        </div>

        {/* 主内容骨架屏 */}
        <div className="flex-1">
          <Container className="py-12">
            <Skeleton className="h-12 w-3/4 mb-4" />
            <Skeleton className="h-4 w-1/2 mb-8" />
            <div className="space-y-4">
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-full" />
              <Skeleton className="h-4 w-5/6" />
            </div>
          </Container>
        </div>
      </div>
    );
  }

  // 错误状态
  if (error || !doc) {
    return (
      <Container className="py-12 text-center">
        <div className="max-w-md mx-auto">
          <h1 className="text-2xl font-bold mb-4">文档不存在</h1>
          <p className="text-muted-foreground mb-6">
            抱歉，您访问的文档不存在或已被删除
          </p>
          <div className="flex items-center justify-center gap-4">
            <Button variant="outline" onClick={() => navigate(-1)}>
              <ArrowLeft className="size-4 mr-2" />
              返回上一页
            </Button>
            <Link to="/documentation">
              <Button>
                <Home className="size-4 mr-2" />
                回到首页
              </Button>
            </Link>
          </div>
        </div>
      </Container>
    );
  }

  // 全屏模式渲染
  if (isFullscreen) {
    return (
      <div id="fullscreen-container" className="fixed inset-0 z-50 bg-background overflow-y-auto">
        {/* 全屏模式顶部工具栏 */}
        <div className="sticky top-0 bg-background z-20 border-b">
          <Container className="py-4 max-w-full">
            <div className="flex items-center justify-between">
              <h1 className="text-2xl font-bold">{doc.title}</h1>
              <div className="flex items-center gap-2">
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleExportPdf}
                  disabled={isExporting || contentLoading}
                  title="导出为 PDF"
                >
                  {isExporting ? (
                    <>
                      <Loader2 className="size-4 mr-2 animate-spin" />
                      导出中...
                    </>
                  ) : (
                    <>
                      <FileDown className="size-4 mr-2" />
                      导出 PDF
                    </>
                  )}
                </Button>
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsFullscreen(false)}
                  title="退出全屏 (ESC)"
                >
                  <X className="size-5" />
                </Button>
              </div>
            </div>
          </Container>
        </div>

        {/* 全屏内容区 */}
        <div className="flex justify-center">
          <Container className="py-8 max-w-full flex gap-8">
            {/* 文档主内容 */}
            <div className="flex-1 min-w-0">
              <article className="prose prose-lg prose-slate dark:prose-invert max-w-none">
                {contentLoading ? (
                  <div className="text-center py-8">
                    <p className="text-muted-foreground">正在加载内容...</p>
                  </div>
                ) : (
                  <MarkdownRenderer content={loadedContent} />
                )}
              </article>
            </div>

            {/* 右侧目录 */}
            <aside className="hidden xl:block w-72 2xl:w-80 flex-shrink-0 sticky top-20 h-fit">
              <div className="p-4 border rounded-lg bg-card">
                <TableOfContents content={loadedContent} scrollOffset={100} isFullscreen={true} />
              </div>
            </aside>
          </Container>
        </div>
        
      </div>
    );
  }

  return (
    <div className="flex min-h-screen bg-background">
      {/* 左侧导航 */}
      <aside className="hidden lg:block w-64 border-r bg-card sticky top-0 h-screen overflow-y-auto">
        <DocNav
          categories={categories}
          currentSlug={slug}
        />
      </aside>

      {/* 主内容区 */}
      <main className="flex-1 min-w-0">
        <Container className="py-8 lg:py-12 max-w-full">
          {/* 面包屑 */}
          <Breadcrumb className="mb-6">
            <BreadcrumbList>
              <BreadcrumbItem>
                <BreadcrumbLink asChild>
                  <Link to="/documentation">
                    <Home className="size-4" />
                  </Link>
                </BreadcrumbLink>
              </BreadcrumbItem>
              <BreadcrumbSeparator />
              {/* 渲染完整的分类层级路径 */}
              {getCategoryPath.map((cat, index) => (
                <React.Fragment key={cat.id}>
                  <BreadcrumbItem>
                    <BreadcrumbLink asChild className="max-w-[200px] truncate">
                      <Link to={`/documentation?category=${cat.id}`}>
                        {cat.name}
                      </Link>
                    </BreadcrumbLink>
                  </BreadcrumbItem>
                  <BreadcrumbSeparator />
                </React.Fragment>
              ))}
              <BreadcrumbItem>
                <BreadcrumbPage className="max-w-[300px] truncate">{doc.title}</BreadcrumbPage>
              </BreadcrumbItem>
            </BreadcrumbList>
          </Breadcrumb>

          {/* 文档头部 */}
          <header className="mb-8 pb-6 border-b">
            <div className="flex items-start justify-between mb-4">
              <h1 className="text-4xl font-bold flex-1">{doc.title}
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsFullscreen(true)}
                  title="全屏显示"
                >
                  <Maximize2 className="size-4" />
                </Button></h1>

              {/* 操作按钮 */}
              <div className="flex items-center gap-2 flex-shrink-0 ml-4">
                {/* <Button
                  variant="ghost"
                  size="sm"
                  onClick={() => setIsFullscreen(true)}
                  title="全屏显示"
                >
                  <Maximize2 className="size-4" />
                </Button> */}
                
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleExportPdf}
                  disabled={isExporting || contentLoading}
                  title="导出为 PDF"
                >
                  {isExporting ? (
                    <Loader2 className="size-4 animate-spin" />
                  ) : (
                    <FileDown className="size-4" />
                  )}
                </Button>
                
                <Button
                  variant="ghost"
                  size="sm"
                  onClick={handleShare}
                  title="分享"
                >
                  <Share className="size-4" />
                </Button>

                <Link to={`/documentation/edit/${doc.id}`}>
                  <Button variant="outline" size="sm">
                    <Edit className="size-4 mr-2" />
                    编辑
                  </Button>
                </Link>
              </div>
            </div>

            {/* 摘要 */}
            {doc.summary && (
              <p className="text-lg text-muted-foreground mb-4">
                {doc.summary}
              </p>
            )}

            {/* 元信息 */}
            <div className="flex flex-wrap items-center gap-4 text-sm text-muted-foreground">
              {/* 作者 */}
              <div className="flex items-center gap-2">
                <User className="size-4" />
                <span>{doc.author}</span>
              </div>

              {/* 更新时间 */}
              <div className="flex items-center gap-2">
                <Calendar className="size-4" />
                <span>更新于 {formatDate(doc.updatedAt)}</span>
              </div>

              {/* 浏览量 */}
              <div className="flex items-center gap-2">
                <Eye className="size-4" />
                <span>{doc.viewCount} 次浏览</span>
              </div>

              {/* 点赞 */}
              <div className="flex items-center gap-2">
                <ThumbsUp className="size-4" />
                <span>{doc.likeCount} 赞</span>
              </div>

              {/* 状态 */}
              <Badge
                variant={doc.status === 'published' ? 'default' : 'secondary'}
              >
                {doc.status === 'published' ? '已发布' : '草稿'}
              </Badge>
            </div>

            {/* 标签 */}
            {doc.tags && doc.tags.length > 0 && (
              <div className="flex flex-wrap items-center gap-2 mt-4">
                {doc.tags.map((tag, index) => (
                  <Badge key={index} variant="outline" className="text-xs">
                    {tag}
                  </Badge>
                ))}
              </div>
            )}
          </header>

          {/* 文档内容 */}
          <article className="prose prose-lg prose-slate dark:prose-invert w-full style={{ maxWidth: '100%' }}">
          {/* <article className="prose prose-lg prose-slate dark:prose-invert max-w-none"> */}
            {contentLoading ? (
              <div className="text-center py-8">
                <p className="text-muted-foreground">正在加载内容...</p>
              </div>
            ) : (
              <MarkdownRenderer content={loadedContent} />
            )}
          </article>

          {/* Phase 3: 附件管理区域（只读模式） */}
          <div className="mt-12 pt-6 border-t">
            <div className="flex items-center justify-between mb-4">
              <h2 className="text-xl font-semibold flex items-center gap-2">
                <Paperclip className="size-5" />
                附件 ({files.length})
              </h2>
              {/* 文档详情页不显示上传按钮，需要编辑请点击"编辑文档" */}
            </div>
            <FileList
              files={files}
              documentId={docData?.id}
              isLoading={filesLoading}
              onRefresh={refetchFiles}
              allowEdit={false}
              markdownContent={loadedContent}
            />
          </div>

          {/* 文档底部 */}
          <footer className="mt-12 pt-6 border-t">
            <div className="flex items-center justify-between">
              <div className="text-sm text-muted-foreground">
                <p>最后更新于 {formatDate(doc.updated_at)}</p>
                {doc.created_at !== doc.updated_at && (
                  <p className="mt-1">
                    创建于 {formatDate(doc.created_at)}
                  </p>
                )}
              </div>

              <div className="flex items-center gap-2">
                <Button variant="outline" size="sm" onClick={() => navigate(-1)}>
                  <ArrowLeft className="size-4 mr-2" />
                  返回
                </Button>
                <Link to={`/documentation/edit/${doc.id}`}>
                  <Button size="sm">
                    <Edit className="size-4 mr-2" />
                    编辑文档
                  </Button>
                </Link>
              </div>
            </div>
          </footer>
        </Container>
      </main>

      {/* 右侧目录 */}
      <aside className="hidden xl:block w-64 xl:w-72 2xl:w-80 sticky top-0 h-screen overflow-y-auto border-l">
        <div className="p-4">
          <TableOfContents content={loadedContent} isFullscreen={false} />
        </div>
      </aside>

      {/* 文档详情页不显示上传对话框，附件管理在编辑页面进行 */}
      
    </div>
  );
};

export default DocDetailPage;

